package com.xiangyi.teachingsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangyi.teachingsystem.Exception.ArgVerifyException;
import com.xiangyi.teachingsystem.dao.*;
import com.xiangyi.teachingsystem.entity.po.Course;
import com.xiangyi.teachingsystem.entity.po.CourseUser;
import com.xiangyi.teachingsystem.entity.vo.Result;
import com.xiangyi.teachingsystem.service.CourseUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CourseUserServiceImpl extends ServiceImpl<CourseUserMapper, CourseUser> implements CourseUserService {
    @Autowired
    CourseUserMapper courseUserMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CourseMapper courseMapper;

    @Override
    @Transactional
    public void addUsersToCourse(List<CourseUser> courseUsers) {
        synchronized (courseUsers) {
            for (CourseUser courseUser : courseUsers) {
                if (courseMapper.selectOne(new QueryWrapper<Course>().eq("sign",courseUser.getSign()))==null)
                    throw new ArgVerifyException("课程sign不存在");
                if (userMapper.selectById(courseUser.getUserId())==null)
                    throw new ArgVerifyException("用户userId不存在");
                courseUserMapper.insert(courseUser);
            }
        }
    }

    @Override
    public Result joinCourseUser(Integer userId, String sign) {
        if (courseMapper.selectOne(new QueryWrapper<Course>().eq("sign",sign))==null)
            return Result.failure("课程不存在，请检查输入的课程标识码");
        courseUserMapper.insert(new CourseUser(sign,userId));
        return Result.success("课程添加成功");
    }

    @Override
    public List<CourseUser> usersList(Integer courseId) {
        return courseUserMapper.usersList(courseId);
    }

    @Override
    public List<Course> joinCourseList(Integer userId) {
        return courseUserMapper.joinCourseList(userId);
    }

}
